package kr.co.exight.onApp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import library.ActionClass;
import library.ExPreferenceManager;
import library.HtmlProgressManager;
import library.Library;
import library.MyTimeData;
import library.Variables;
import library.YonseiAuthorizer;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import struct.SubjectInfo;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ActivityTimeTable extends Activity {

	/** Called when the activity is first created. */

	private WebView wv;
	private LinearLayout llMon;
	private LinearLayout llTime;
	private LinearLayout llTue;
	private LinearLayout llWed;
	private LinearLayout llThu;
	private LinearLayout llFri;
	private Object result;

	public static  int maxTimeLine = 12;

	private ExPreferenceManager preferManager;
	private MyTimeData myData;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.act_timetable);

		llTime = (LinearLayout)findViewById(R.id.timetable_llTime);
		llMon = (LinearLayout)findViewById(R.id.timetable_llMonday);
		llTue = (LinearLayout)findViewById(R.id.timetable_llTuesday);
		llWed = (LinearLayout)findViewById(R.id.timetable_llWednesday);
		llThu = (LinearLayout)findViewById(R.id.timetable_llThursday);
		llFri = (LinearLayout)findViewById(R.id.timetable_llFriday);

		Button btnRefresh = (Button)findViewById(R.id.timetable_btnRefresh);



		// TODO Auto-generated method stub
		//wv = (WebView)findViewById(R.id.timetable_wv);
		preferManager = new ExPreferenceManager(this);
		myData = new MyTimeData(MyTimeData.DBNAME_TIMETABLE, this);

		btnRefresh.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				myData.removeRow(MyTimeData.DBNAME_TIMETABLE);
				showDialog(0);
				startTimeTableParsing();
			}
		});

		//	wv.setVisibility(View.GONE);

		if(preferManager.getItem(ExPreferenceManager.TAG_TIMETABLE_WRITE) == ""){
			startTimeTableParsing();

		}else {
			result = myData.getResDataFromDB();
			mHandler.sendEmptyMessage(0);
		}
	}

	private InputStream crawlFromPortal(HttpClient paramHttpClient, int paramInt1, int paramInt2)
			throws IOException{
		HttpPost localHttpPost = new HttpPost("https://underwood1.yonsei.ac.kr/haksa/SG/sg13_r090.jsp");
		ArrayList localArrayList = new ArrayList();
		Object[] arrayOfObject = new Object[2];
		arrayOfObject[0] = Integer.valueOf(paramInt1);
		arrayOfObject[1] = Integer.valueOf(paramInt2);

		localArrayList.add(new BasicNameValuePair("fndhyhg", String.format("%d%d", arrayOfObject)));
		localArrayList.add(new BasicNameValuePair("strRet", "start"));
		localArrayList.add(new BasicNameValuePair("returnPage", "sg13_r090.jsp"));
		localArrayList.add(new BasicNameValuePair("dbMode", "S"));
		localArrayList.add(new BasicNameValuePair("master_id", "630"));
		localArrayList.add(new BasicNameValuePair("sub_id", "20"));
		localHttpPost.setEntity(new UrlEncodedFormEntity(localArrayList, "UTF-8"));
		return paramHttpClient.execute(localHttpPost).getEntity().getContent();
		
	}


	public void startTimeTableParsing(){
		showDialog(0);

		Thread thread = new Thread(new Runnable() {
			
			public void run() {
				// TODO Auto-generated method stub
				YonseiAuthorizer auth = new YonseiAuthorizer();
				auth.authorize(Variables.LOGIN_ID, Variables.PASSWORD);
				Timestamp time = Library.getCurrentTimeStamp();
				int year = time.getYear() + 1900;
				int month = time.getMonth();
				
				int[] arrayOfInt = new int[12];
			      arrayOfInt[0] = 2;
			      arrayOfInt[1] = 1;
			      arrayOfInt[2] = 1;
			      arrayOfInt[3] = 1;
			      arrayOfInt[4] = 1;
			      arrayOfInt[5] = 1;
			      arrayOfInt[6] = 1;
			      arrayOfInt[7] = 2;
			      arrayOfInt[8] = 2;
			      arrayOfInt[9] = 2;
			      arrayOfInt[10] = 2;
			      arrayOfInt[11] = 2;
			    if(month == 12) month = 0;
			    
			    int hakgi = arrayOfInt[month];
			    
			    try {
					InputStream is = crawlFromPortal(auth.getAuthorizedHttpClient(), year, hakgi);
					String result = convertStreamToString(is);
					Message msg = new Message();
					msg.obj = result;
					msg.what = 1;
					mHandler.sendMessage(msg);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Log.d("ERROR" , e.toString());
				}
			}
		});
		thread.start();


		/*
		YonseiManager.getTimeTableText(wv, new ActionClass(this) {

			// Yscec로그인되었을때에 동작
			@Override
			public void actionSuccess() {
				// TODO Auto-generated method stub
				wv.loadUrl(Variables.YONSEI_TIMETABLE_URL);
			}

			@Override // 시간표받아왔을때의 동작
			public void actionSuccess(Object object) { // 
				// TODO Auto-generated method stub
				startHtmlParser((String)object);
			}

			@Override
			public void actionFailed() {
				// TODO Auto-generated method stub
				try{
					dismissDialog(0);
				}catch(IllegalArgumentException e){
					e.printStackTrace();
				}
				Library.makeYesDialog(ActivityTimeTable.this, "인터넷 연결이 좋지 않습니다.\n연결을 확인해주세요", "확인", new DialogChoiceYes() {

					public boolean choiceYes() {
						// TODO Auto-generated method stub
						onBackPressed();
						return false;
					}
				});
			}

		}, Variables.LOGIN_ID, Variables.PASSWORD);*/
	}
	private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "EUC-KR"));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 0:
				HashMap<String, ArrayList<SubjectInfo>> data = (HashMap<String, ArrayList<SubjectInfo>>)result;
				ArrayList<TextView> tvList = null;
				int backgroundResource = R.drawable.textlines;
				String day = Library.getDayOfTheWeekFromDate(Library.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss");

				for(Map.Entry map : data.entrySet()){
					if(map.getKey().equals(day)) backgroundResource = R.drawable.textlines_day;
					else backgroundResource = R.drawable.textlines;

					tvList = new ArrayList<TextView>();
					TextView tvEmpty = null;

					for(int i = 0 ; i < maxTimeLine; i++){
						tvEmpty = new TextView(ActivityTimeTable.this);
						tvEmpty.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,getPixelRelateDip(57)));
						tvEmpty.setBackgroundResource(backgroundResource);
						tvList.add(tvEmpty);
					} 

					if(maxTimeLine > 12){
						for(int i = 13; i < maxTimeLine+1; i++ ){
							tvEmpty = new TextView(ActivityTimeTable.this);
							tvEmpty.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,getPixelRelateDip(57)));
							tvEmpty.setTextSize(12);
							tvEmpty.setTextColor(Color.BLACK);
							tvEmpty.setGravity(android.view.Gravity.CENTER);
							StringBuilder builder = new StringBuilder();
							builder.append(i-4);
							builder.append(":00");
							builder.append("\n");
							builder.append("(" + i + ")");

							tvEmpty.setText(builder);

							Library.setFontNanumGothic(tvEmpty);

							llTime.addView(tvEmpty);
						}
					}
					// textview 초기화

					ArrayList<SubjectInfo> arrData = (ArrayList<SubjectInfo>)map.getValue();

					SubjectInfo sub = null;
					TextView tvSubject = null;

					if(arrData != null){
						for(int i = 0 ; i < arrData.size(); i++){
							sub = arrData.get(i);
							ArrayList<Integer> a = sub.getArrTime();
							int size = a.size();

							for(int t = 0; t < size; t++){
								tvSubject = new TextView(ActivityTimeTable.this);
								tvSubject.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,getPixelRelateDip(57)));
								tvSubject.setGravity(android.view.Gravity.CENTER);
								tvSubject.setTextColor(Color.GRAY);
								tvSubject.setTextSize(12);
								tvSubject.setText("");
								tvSubject.append(Library.setStringSize(sub.getName(), getPixelRelateDip(10)));
								tvSubject.append("\n");

								tvSubject.append(Library.setStringColor(sub.getSite(), "black"));
								Library.setTextViewBold(tvSubject);

								tvSubject.setBackgroundResource(backgroundResource);
								Library.setFontNanumGothic(tvSubject);

								tvList.set(a.get(t)-1, tvSubject);
							}
						}
					}

					LinearLayout targetll = null;
					if(map.getKey().equals("월")){
						llMon.removeViewsInLayout(1, llMon.getChildCount()-1);
						targetll = llMon;
					}else if(map.getKey().equals("화")){
						llTue.removeViewsInLayout(1, llTue.getChildCount()-1);
						targetll = llTue;
					}else if(map.getKey().equals("수")){
						llWed.removeViewsInLayout(1, llWed.getChildCount()-1);
						targetll = llWed;
					}else if(map.getKey().equals("목")){
						llThu.removeViewsInLayout(1, llThu.getChildCount()-1);
						targetll = llThu;
					}else if(map.getKey().equals("금")){
						llFri.removeViewsInLayout(1, llFri.getChildCount()-1);
						targetll = llFri;
					}우미

					for(int i = 0; i < tvList.size(); i++){
						targetll.addView(tvList.get(i));
					}
				}

				break;
				
			case 1:
				startHtmlParser((String)msg.obj);
				break;
				
			}
		};
	};


	@Override // 로딩바 안보이게 하기
	protected Dialog onCreateDialog(int id) {
		final Dialog dialog = new Dialog(this, R.style.Theme_Dialog);
		View view = getLayoutInflater().inflate(R.layout.dialog_progress, null);
		dialog.setContentView(view);

		dialog.setOnCancelListener(new OnCancelListener() {

			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				finish();

			}

		});
		return dialog;

	}


	public void startHtmlParser(String text){
		HtmlProgressManager htmlProgress = new HtmlProgressManager(new ActionClass(this) {
			@Override
			public void actionSuccess(Object object) {
				// TODO Auto-generated method stub
				myData.pushTableDataToDB(MyTimeData.DBNAME_TIMETABLE, (HashMap<String, ArrayList<SubjectInfo>>)result);

				preferManager.putItem(ExPreferenceManager.TAG_TIMETABLE_WRITE, "TRUE");
			}
			public Object doParse(String textData) {
				// TODO Auto-generated method stub

				Source source = new Source(textData);

				source.fullSequentialParse();

				Iterator trIter = source.getAllElements(HTMLElementName.TABLE).get(6).
						getAllElements(HTMLElementName.TR).iterator();

				trIter.next();
				trIter.next();
				trIter.next();

				String floorName = null;
				int time = 0; // 교시 초기화
				String[] day = new String[]{"월","화","수","목","금"};

				HashMap<String , ArrayList<SubjectInfo>> hashData = new HashMap<String, ArrayList<SubjectInfo>>();
				while(trIter.hasNext()){ // TR 안으로 들어감

					++time; //교시 1 더함

					Iterator dataIter =  ((Element)trIter.next()).getAllElements(HTMLElementName.TD).iterator();

					dataIter.next(); // 시간은 파싱할필요없다.

					int dayCount = 0;
					//요일 초기화 설정
					String value[] = null;

					while(dataIter.hasNext()){ // TD 안으로 들어간다
						boolean isTwoTable = false;
						value = ((Element)dataIter.next()).getContent().getTextExtractor().toString().split(" ");

						if(value.length > 5){
							isTwoTable = true;
						}

						if(value.length == 0 || dayCount == 5  || dayCount == 6){
							dayCount++;
							continue;					    	
						}else {

							ArrayList<SubjectInfo> arrSub = hashData.get(day[dayCount]);
							if( arrSub != null ){
								boolean isContinue = false;

								int continueIndex = 0;
								for(int i = 0; i < arrSub.size(); i++){
									if(value[1].equals(arrSub.get(i).getName())) {
										isContinue = true;
										continueIndex = i;
										break;
									}
								}

								if(isContinue){ // 연속일때!! // 과목이 연속
									if(isTwoTable){
										arrSub.get(continueIndex).setSite(arrSub.get(continueIndex).getSite() + "/" + value[value.length-1]);
									}
									arrSub.get(continueIndex).getArrTime().add(time);
									if(time > maxTimeLine) maxTimeLine = time;
								}else { // 처음나오는겨 // 과목이 처음

									SubjectInfo sub = new SubjectInfo();
									sub.setName(value[1]);
									sub.setSite(value[2]);

									if(isTwoTable){
										sub.setSite(value[2] + "/" + value[value.length-1]);
									}
									ArrayList<Integer> a = new ArrayList<Integer>();
									a.add(time);
									sub.setArrTime(a);
									if(time > maxTimeLine) maxTimeLine = time;
									arrSub.add(sub);
								}
							}else { // 아예 맨처음에 해시맵만들떄

								arrSub = new ArrayList<SubjectInfo>();
								hashData.put(day[dayCount], arrSub);

								SubjectInfo sub = new SubjectInfo();
								sub.setName(value[1]);
								sub.setSite(value[2]);

								if(isTwoTable){
									sub.setSite(value[2] + "/" + value[value.length-1]);
								}

								ArrayList<Integer> a = new ArrayList<Integer>();
								a.add(time);
								if(time > maxTimeLine) maxTimeLine = time;
								sub.setArrTime(a);

								arrSub.add(sub);
							}	
							dayCount++;
						}
					}
				}

				try{
					dismissDialog(0);
				}catch(IllegalArgumentException e){
					e.printStackTrace();
				}
				// 시간표가 없을경우 다 채워줌.		
				if(!hashData.containsKey("월")){
					
					hashData.put("월", null);
					
				}else if(!hashData.containsKey("화")){
					hashData.put("화", null);
					
				}else if(!hashData.containsKey("수")){
					hashData.put("수", null);
				}else if(!hashData.containsKey("목")){
					hashData.put("목", null);
				}else if(!hashData.containsKey("금")){
					hashData.put("금", null);

				}

				result = hashData;
				mHandler.sendEmptyMessage(0);
				return hashData;
			}
		}, text);
		htmlProgress.start();

	}

	public int getPixelRelateDip(int dip){
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		float dip_scale = outMetrics.density;

		return (int)((float)dip * dip_scale);
	}



}
